<template>
    <uni-section :title="formItem.t_name" type="line">
        <view class="uni-px-5 uni-pb-5">
            <uni-data-checkbox v-model="radio" :localdata="radioArr2" @change="changeRadio"></uni-data-checkbox>
        </view>
    </uni-section>
</template>

<script lang="ts" setup>
	
    import { ref, watch } from 'vue'

    const props = defineProps({
        formItem: {
            type: Object,
            required: true
        },
		ws:
		{
			type:WebSocket,
			required:true
		},
		device:{
			type:Number,
			required:true
		}
    })

  //   const switchbox = [
  //       { text: '一档', value: 0 },
  //       { text: '二档', value: 1 },
		// { text: '三档', value: 2 },
		// {text : "关" ,value:3},
  //   ];

	// props.formItem.f_value 格式为 
	// XX:S1|XX:S2|XX:S3|XX:stop

	// 格式化 props.formItem.f_value 为数组
	const radioArr = props.formItem.f_value.split("|");
	// 格式化数组为对象
	const radioObj = {};
	radioArr.forEach(item => {
		const [key, value] = item.split(":");
		radioObj[key] = value;
	});
	// 格式化对象为数组
	const radioArr2 = ref([]);
	for (let key in radioObj) {
		radioArr2.value.push({ text: key, value: radioObj[key] });
	}
		
    // 根据 props.formItem.value 初始化 radio.value
	const radio = ref(props.formItem.value);
	// 监听 props.formItem.value 的变化并更新 radio.value
    watch(() => props.formItem.value, (newValue) => {
        if(props.formItem.value =="S1")
        {
        	radio.value=1
        }else if(props.formItem.value =="S2")
        {
			radio.value=2
        }
		else if(props.formItem.value =="S3")
		{
			radio.value=3
		}
		// else{
		// 	radio.value=0
		// }
		//radio.value = newValue === "on" ? 0 : 1;
    });
	
    const changeRadio = (evt) => {
        radio.value = evt.detail.value;
		let Rvalue;
		console.log(radio.value)
		if(radio.value=="on")
		{
			Rvalue="on"
		}
		else 
		{
			Rvalue="off"
		}
        props.ws.send({data:
            JSON.stringify({
                page: 5,
                type: -1,
                value: Rvalue, // 确保发送的值是 "on" 或 "off"
                config_id: props.formItem.id,
                d_no: props.device,
				log:props.formItem.t_name+ Rvalue
            })}
        );
    };
</script>
